package com.party.mobile.web.controller.analysis;

import com.party.common.utils.PartyCode;
import com.party.common.utils.StringUtils;
import com.party.core.model.YesNoStatus;
import com.party.core.model.analysis.StatisticsEvent;
import com.party.core.model.analysis.StatisticsPageFlow;
import com.party.core.service.analysis.IStatisticsEventService;
import com.party.core.service.analysis.IStatisticsPageFlowService;
import com.party.mobile.biz.analysis.StatisticalEventFlowBizService;
import com.party.mobile.biz.analysis.StatisticsFlowBizService;
import com.party.mobile.biz.analysis.StatisticsUserBizService;
import com.party.mobile.web.dto.AjaxResult;
import com.party.mobile.web.dto.analysis.EventFlowInput;
import com.party.mobile.web.dto.analysis.PageFlowInput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 分析流程
 *
 * @author yifeng
 * @date 2018/8/3 0003
 * @time 下午 16:56
 */
@Controller
@RequestMapping("analysis/flow")
public class StatisticalFlowController {
    @Autowired
    private IStatisticsPageFlowService statisticsPageFlowService;
    @Autowired
    private StatisticsFlowBizService statisticsFlowBizService;
    @Autowired
    private StatisticalEventFlowBizService statisticalEventFlowBizService;
    @Autowired
    private IStatisticsEventService statisticsEventService;
    @Autowired
    private StatisticsUserBizService statisticsUserBizService;

    Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 进入页面时保存记录
     *
     * @param flowInput 输入参数
     * @param response  response
     * @param request   request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "innerPageDataReport")
    public AjaxResult innerPageDataReport(PageFlowInput flowInput, HttpServletResponse response, HttpServletRequest request) {
        try {
            //获取当前访问用户的userId
            String userId = statisticsUserBizService.userLoginRecordOperation("", "", "", request);

            if (StringUtils.isEmpty(userId)) {
                return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "用户编号不能为空");
            }
            flowInput.setUserId(userId);
            String uniqueCode = statisticsFlowBizService.getCookieUniqueCode(request, statisticsFlowBizService.pageRedisKey);
            if (StringUtils.isEmpty(flowInput.getParentId()) || StringUtils.isEmpty(uniqueCode)) {
                /**
                 * 如果上个页面为空，说明是新的一次访问。则重新生成一次uniqueCode
                 */
                uniqueCode = statisticsFlowBizService.getUniqueCode(flowInput.getHtmlUrl(), userId);
            }
            flowInput.setUniqueCode(uniqueCode);

            /**
             * 如果uniqueCode为空，上一次的记录id为空，说明之前访问过
             * 如果之前访问的记录isEnd不是结束，更新为结束
             */
            if (StringUtils.isEmpty(flowInput.getParentId()) && StringUtils.isNotEmpty(flowInput.getFlowId())) {
                try {
                    StatisticsPageFlow lastPageFlow = statisticsPageFlowService.get(flowInput.getFlowId());
                    if (lastPageFlow != null && !YesNoStatus.YES.getCode().equals(lastPageFlow.getIsEnd())) {
                        lastPageFlow.setIsEnd(YesNoStatus.YES.getCode());
                        statisticsPageFlowService.update(lastPageFlow);
                    }
                } catch (Exception e) {
                    logger.error("更新上次访问记录isEnd为1失败", e);
                }
            }

            Cookie cookie = new Cookie(statisticsFlowBizService.pageRedisKey, uniqueCode);
            cookie.setPath("/");
            response.addCookie(cookie);

            String flowId = statisticsFlowBizService.insertPageFlow(flowInput, request);
            return AjaxResult.success((Object) flowId);
        } catch (Exception e) {
            logger.error("进入页面时触发接口异常", e);
            return AjaxResult.error();
        }
    }

    /**
     * 进入页面时更新机构id
     *
     * @param flowInput 输入参数
     * @return
     */
    @ResponseBody
    @RequestMapping("updatePartnerId")
    public AjaxResult updatePartnerId(PageFlowInput flowInput) {
        try {
            statisticsFlowBizService.updatePagePartnerId(flowInput);
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("进入页面时更新机构id触发接口异常", e);
            return AjaxResult.error();
        }
    }

    /**
     * 离开页面时更新记录
     *
     * @param flowInput 输入参数
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "outputPageDataReport")
    public AjaxResult outputPageDataReport(PageFlowInput flowInput, HttpServletRequest request) {
        try {
            statisticsFlowBizService.updatePageStayTime(flowInput, request);
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("离开页面时触发接口异常", e);
            return AjaxResult.error();
        }
    }

    /**
     * 统计事件流程,进入埋点页面时触发
     *
     * @param eventflowInput 输入参数
     * @param response       response
     * @param request        request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "innerEventFlowDataReport")
    public AjaxResult innerEventFlowDataReport(EventFlowInput eventflowInput, HttpServletResponse response, HttpServletRequest request) {
        String userId, code, pCode, orgId;
        try {
            //获取当前访问用户的userId
            userId = statisticsUserBizService.userLoginRecordOperation("", "", "", request);
            if (StringUtils.isEmpty(userId)) {
                throw new Exception("用户编号为空");
            }
            code = eventflowInput.getCode();
            pCode = eventflowInput.getpCode();
            orgId = eventflowInput.getOrgId();

            if ("".equalsIgnoreCase(code)) {
                return AjaxResult.error(PartyCode.DATA_UNEXIST, "事件Code为空");
            }
            StatisticsEvent statisticsEvent = statisticsEventService.getByCode(code);
            if (null == statisticsEvent) {
                return AjaxResult.error(PartyCode.DATA_UNEXIST, "事件Code不存在");
            }

            statisticalEventFlowBizService.innerEventFlowDataReport(statisticsEvent.getId(), pCode, orgId, userId, request, response);
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("进入埋点页面触发接口异常", e);
            return AjaxResult.error();
        }
    }
}
